package com.example.gatewayservice.Filters;

import com.example.gatewayservice.Service.Activity;
import com.example.gatewayservice.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    public static final String[] excludeKeywords = {"/users/login", "/users/register",
            "/CommonTest/test", "/StudentTest/test", "/TeacherTest/test", "/AdminTest/test", "/AiTest/test", "/*"};
    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("全局过滤器已启动！！！test");
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        // 2.判断当前请求是否需要被拦截
        if (isAllowPath(path)) {
            // 无需拦截，放行
            log.info("登录或其他操作直接放行");
            return chain.filter(exchange);
        }
        // 3.获取token
        String bearerToken = null;
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if (headers != null && !headers.isEmpty()) {
            bearerToken = headers.get(0);
            if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
                // 提取 token 部分
                token = bearerToken.substring(7);
            }
        }
        //  检查是否携带 token（不验证有效性）
        if (token == null || token.isEmpty()) {
            log.info("未携带token");
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 401
            return response.setComplete();
        }
        // 4.解析token
        String userId = null;
        String role = null;
        try {
            JwtTool.ParsedToken parsedToken = JwtTool.parseAndValidateToken(token);
            userId = parsedToken.getUserId();
            role = parsedToken.getRole();
            System.out.println("userId = " + userId);
        } catch (Exception e) {
            log.info("token解析失败");
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//401
            return response.setComplete();
        }
        // 新增逻辑：记录用户活跃度（根据角色区分）
        System.out.println("角色："+role);
        if ("TEACHER".equals(role) || "STUDENT".equals(role) || "student".equals(role) || "teacher".equals(role)) {
            Activity.recordUserActivity(userId, role, path, request);
        }
        // 5.传递用户信息到下游服务
        String userInfo = userId;
        String roleInfo = role;
        ServerWebExchange exc = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .request(builder -> builder.header("role-info", roleInfo))
                .build();
        // 6.放行
        return chain.filter(exc);
    }


    private boolean isAllowPath(String path) {
        if (path == null) {
            return false;
        }
        for (String keyword : excludeKeywords) {
            if (path.contains(keyword)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public int getOrder() {
        //值越小优先级越高
        return 0;
    }


}
